package ai

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"smartposts/internal/pb"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const serverAddr string = "ai_service:50051"

func Ask(ctx context.Context, query string, postContent string, postTitle string) (<-chan string, error) {
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}

	conn, err := grpc.NewClient(serverAddr, opts...)
	if err != nil {
		return nil, fmt.Errorf("failed to connect to gRPC server: %w", err)
	}

	client := pb.NewRagServiceClient(conn)

	postJSON, err := json.Marshal(map[string]string{
		"content": postContent,
		"title":   postTitle,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to marshal post content: %w", err)
	}

	stream, err := client.AskWithContent(ctx, &pb.Query{
		Query:   query,
		Content: string(postJSON),
	})
	if err != nil {
		return nil, fmt.Errorf("failed to call AskWithContent: %w", err)
	}

	ch := make(chan string)
	go func() {
		defer conn.Close()
		defer close(ch)
		for {
			resp, err := stream.Recv()
			if err == io.EOF {
				break
			}
			if err != nil {
				log.Printf("Error receiving from stream: %v", err)
				break
			}
			ch <- resp.GetAnswer()
		}
	}()

	return ch, nil
}

